package com.github.cyf.waf;

import com.github.cyf.config.properties.WafProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.unit.DataSize;

import javax.servlet.DispatcherType;

/**
 * @author chenyifan
 * @create 2024-11-14 10:38
 */
@Configuration
public class WafFilterConfig {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSizeStr;

    @Bean
    public MultipartRequestChecker multipartRequestChecker(WafProperties wafProperties) {
        MultipartRequestChecker checker = new MultipartRequestChecker();
        checker.setAllowFileType(wafProperties.getAllowFileType());
        if (maxFileSizeStr != null) {
            long maxFileSize = DataSize.parse(maxFileSizeStr).toBytes();
            checker.setMaxFileSize(maxFileSize);
        }
        return checker;
    }

    @Bean
    public FilterRegistrationBean<WafFilter> xssFilterRegistration(WafProperties wafProperties, MultipartRequestChecker multipartRequestChecker) {
        WafFilter wafFilter = new WafFilter();
        wafFilter.setExcludes(wafProperties.getExcludes());
        wafFilter.setMultipartRequestChecker(multipartRequestChecker);
        FilterRegistrationBean<WafFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(wafFilter);
        registration.addUrlPatterns("/*");
        registration.setName("WafFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 100);
        return registration;
    }

}